<template>
	<view
		:style="{
			padding: mpWxPos.logoLeft + 'px'
		}">
		<view :class="`container`">
			<view class="mt-1px">
				<view class="border border-solid border-[#6b7280] rounded">
					<view class="block my-10px mx-auto w-100px h-100px">
						<image
							class="w-100px h-100px"
							:src="userInfo.showAvatar"
							mode="aspectFit"></image>
					</view>
					<button
						class="block my-10px mx-auto text-sm w-100px h-25px leading-25px text-center bg-blue-400 text-white rounded"
						open-type="chooseAvatar"
						@chooseavatar="chooseAvatar">
						选择头像
					</button>
				</view>
				<view class="mt-10px border border-solid border-[#6b7280] rounded">
					<view class="m-10px flex">
						<view class="w-60px text-sm text-gray-800">昵称</view>
						<input
							class="flex-1"
							type="nickname"
							@change="onInputNickName"
							placeholder="请输入昵称"
							v-model="userInfo.showNickname" />
					</view>
					<view class="m-10px flex">
						<view class="w-60px text-sm text-gray-800">手机号</view>
						<view class="flex-1 flex justify-between">
							<view>{{ userInfo.showMobile }}</view>
							<button
								class="p-0 bg-transparent ml-10px after:border-none flex items-center"
								open-type="getPhoneNumber"
								@getphonenumber="getPhoneNumber">
								<uv-icon name="reload" color="#2979ff" size="22"></uv-icon>
							</button>
						</view>
					</view>
				</view>
				<view class="mt-10px space-y-10px">
					<uv-button type="warning" text="重置信息" @tap="showUserInfo"></uv-button>
					<uv-button type="primary" text="保存以上信息" @tap="saveUserInfo"></uv-button>
				</view>
			</view>
		</view>
		<view v-show="cropCanvas.isShow">
			<canvas
				canvas-id="myCanvas"
				:style="{
					width: cropCanvas.width + 'px',
					height: cropCanvas.height + 'px'
				}"></canvas>
		</view>
	</view>
</template>

<script>
export default {
	name: 'user_center_Setting',
	data() {
		return {
			userInfo: {
				showMobile: '',
				showNickname: '',
				showAvatar: ''
			},
			cropCanvas: {
				width: 100,
				height: 100,
				isShow: false
			}
		}
	},
	computed: {
		mpWxPos() {
			return this.$store.getters['mpWxPos/getMpWxPos']
		},
		mpUser() {
			return this.$store.getters['jwt/getMpUser']
		}
	},
	onLoad() {
		this.showUserInfo()
	},
	methods: {
		saveUserInfo() {
			const doSave = (base64Data) => {
				const postData = {}
				if (this.userInfo.showNickname) {
					postData['nickname'] = this.userInfo.showNickname
				}
				if (this.userInfo.showMobile && this.userInfo.showMobile !== '手机号未设置') {
					postData['mobile'] = this.userInfo.showMobile
				}
				if (this.mpUser.avatar !== this.userInfo.showAvatar) {
					postData['avatar'] = base64Data
				}
				this.$api.xcxPost('/user/center/setting', postData).then((res) => {
					uni.$u.toast(res.message)
					this.$store.commit('jwt/updateMpUser', res.data.mpUser)
					this.showUserInfo()
				})
			}

			if (this.mpUser.avatar !== this.userInfo.showAvatar) {
				console.log(this.userInfo.showAvatar, this.mpUser.avatar)
				uni.getFileSystemManager().readFile({
					filePath: this.userInfo.showAvatar,
					encoding: 'base64',
					success: (res) => {
						const base64Data = res.data
						// 从文件路径获取文件扩展名
						const fileExt = this.userInfo.showAvatar.split('.').pop().toLowerCase()
						const mimeType = `image/${fileExt === 'jpg' ? 'jpeg' : fileExt}`
						const fullBase64 = `data:${mimeType};base64,${base64Data}`
						doSave(fullBase64)
					},
					fail: (err) => {
						console.error('转换图片为Base64失败:', err)
					}
				})
			} else {
				doSave()
			}
		},
		showUserInfo() {
			const mpUser = this.mpUser
			if (mpUser) {
				this.userInfo.showMobile = mpUser.mobile || '手机号未设置'
				this.userInfo.showNickname = mpUser.nickname
				this.userInfo.showAvatar = mpUser.avatar
			}
		},
		chooseAvatar(e) {
			this.cropToSquare(e.detail.avatarUrl)
		},
		onInputNickName(e) {
			this.userInfo.showNickname = e.detail.value
		},
		getPhoneNumber(e) {
			// 用户点击了获取手机号按钮
			if (e.detail.errMsg === 'getPhoneNumber:ok') {
				// 用户同意授权获取手机号
				this.$api.xcxPost('/user/center/decrypt-mp-mobile', e.detail).then((res) => {
					this.userInfo.showMobile = res.data.mobile
				})
			} else {
				// 用户拒绝授权
			}
		},
		cropToSquare(tempFilePath) {
			// 获取图片信息，包括图片的宽度和高度
			uni.getImageInfo({
				src: tempFilePath,
				success: (imageInfo) => {
					const { width, height } = imageInfo
					const ratio = width / height
					if (ratio >= 0.8 && ratio <= 1.2) {
						this.userInfo.showAvatar = tempFilePath
					} else {
						// 计算正方形的边长
						const squareSide = Math.min(width, height)
						// 计算裁剪的起始坐标
						const x = (width - squareSide) / 2
						const y = (height - squareSide) / 2
						// 显示画布
						this.cropCanvas.isShow = true
						this.cropCanvas.width = squareSide
						this.cropCanvas.height = squareSide
						// 创建一个画布上下文
						const ctx = uni.createCanvasContext('myCanvas', this)
						// 绘制图片到画布上
						ctx.drawImage(
							tempFilePath,
							x,
							y,
							squareSide,
							squareSide,
							0,
							0,
							squareSide,
							squareSide
						)
						// 将画布内容绘制到屏幕上
						ctx.draw(true, () => {
							// 绘制完成后，使用 uni.canvasToTempFilePath 输出裁剪后的图片
							uni.canvasToTempFilePath({
								canvasId: 'myCanvas',
								success: (res) => {
									// 处理裁剪后的图片，例如保存或上传
									this.userInfo.showAvatar = res.tempFilePath
									this.cropCanvas.isShow = false
								},
								fail: (err) => {
									console.error('裁剪失败:', err)
									this.cropCanvas.isShow = false
								}
							})
						})
					}
				},
				fail: (err) => {
					console.error('获取图片信息失败:', err)
					this.cropCanvas.isShow = false
				}
			})
		}
	}
}
</script>
